﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;
using DBMigrator.Core.DBProviders.Configuration;
using StructureMap;

namespace DBMigrator.Core.DBProviders
{
    public class ProviderFactory : IProviderFactory
    {
        private readonly string environment;

        public ProviderFactory(string environment)
        {
            this.environment = environment;    
        }

        public IProvider GetProvider(string connectionName)
        {
            var connection = GetEnvironmentConnections()[connectionName];

            var provider = ObjectFactory.GetNamedInstance<IProvider>(connection.Provider);
            provider.Initialize(connection.ConnectionString);

            return provider;
        }

        private ConnectionElementCollection GetEnvironmentConnections()
        {
            return (ConnectionElementCollection)ConfigurationManager.GetSection(string.Format(
                "migrationSettings/environments/{0}/databaseConnections", environment));
        }
    }
}
